<template>
  <div class="course-directory">
    <!-- 课程统计 -->
    <div class="course-stats">
      共{{ totalChapters }}个章节 {{ totalActivities }}个活动
    </div>

    <!-- 一级目录列表 -->
    <div class="directory-list">
      <div v-for="chapter in chapters" :key="chapter.id" class="chapter">
        <!-- 一级目录标题 -->
        <div class="chapter-header" @click="toggleChapter(chapter)">
          <i :class="['arrow', chapter.isExpanded ? 'expanded' : '']">▼</i>
          <span class="chapter-title">{{ chapter.chapterName }}</span>

          <span class="chapter-info">
            {{ chapter.activityCount }}个活动
            <el-tag class="space" size="small" type="info">{{ chapter.mode === 0 ? '混合' : chapter.mode === 1 ? '线上' : '线下' }}</el-tag>
            <el-tag class="space" size="small" type="primary">{{ chapter.time }}学时</el-tag>
          </span>
        </div>

        <!-- 二级目录列表 -->
        <div v-if="chapter.isExpanded" class="section-list">
          <div v-for="section in chapter.sections" :key="section.id" class="section">
            <!-- 二级目录标题 -->
            <div class="section-header" @click="toggleSection(section)">
              <i :class="['arrow', section.isExpanded ? 'expanded' : '']">▼</i>
              <span class="section-title">{{ section.chapterName }}</span>
              <span class="section-info">
                {{ section.activityCount }}个活动
                <el-tag class="space" size="small" type="info">{{ section.mode === 0 ? '混合' : chapter.mode === 1 ? '线上' : '线下' }}</el-tag>
                <el-tag class="space" size="small" type="primary">{{ section.time }}学时</el-tag>
              </span>
            </div>

            <!-- 资源列表 -->
            <div v-if="section.isExpanded" class="resource-list">
              <div v-for="resource in section.resources" :key="resource.id" class="resource-item">
                <div class="resource-icon">
                  <i :class="getResourceIcon(resource.type)"></i>
                </div>
                <div class="resource-info">
                  <div class="resource-title">{{ resource.chapterName }}</div>
                  <div class="resource-status">{{ resource.status }}</div>
                </div>
                <el-button
                    size="small"
                    :type="resource.status === '已完成' ? 'success' : 'primary'"
                >
                  {{ resource.status === '已完成' ? '学习回顾' : '继续学习' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { postRequest } from "@/utils/api";

export default {
  name: 'CourseDirectory',
  data() {
    return {
      // 目录数据 包含一级目录、二级目录和二级目录对应的资料
      chapters: [{
        activityCount:'0',
        chapterName:'一级目录',
        time:'0',
        mode:'混合',
        isExpanded:false,
        sections:[{
          activityCount:'0',
          chapterName:'二级目录',
          time:'0',
          mode:'混合',
          isExpanded:false,
          resources:[{
            status: '0',
            chapterName:'三级目录',
            type:'0',
            isExpanded:false,
          }
          ]
        }]
      }],
      totalChapters: 0,
      totalActivities: 0
    }
  },
  created() {
    this.loadAllData();
  },
  methods: {
    // 加载所有数据
    async loadAllData() {
      try {
        const courseId = localStorage.getItem('courseId') || null;
        console.log('课程号' + courseId);

        const res = await postRequest('/courseCatalog/chapters', { courseId });

        if (res && res.data && res.data.code === 200) {
          // 检查 res.data.data.courseCatalog 是否为数组
          const courseCatalog = res.data.data.courseCatalog || [];

          if (Array.isArray(courseCatalog)) {
            // 处理第一层章节（courseCatalog）
            this.chapters = courseCatalog.map(chapter => {
              // 计算每个章节下的第三级目录数量总和
              const chapterActivityCount = chapter.courseCatalogSecond.reduce((total, section) => {
                return total + section.courseCatalogThird.length;
              }, 0);

              return {
                ...chapter,
                isExpanded: false,  // 添加展开状态标志
                activityCount: chapterActivityCount,  // 设置章节的活动数量
                sections: chapter.courseCatalogSecond.map(section => {
                  // 计算每个小节下的第三级目录数量
                  const sectionActivityCount = section.courseCatalogThird.length;

                  return {
                    ...section,
                    isExpanded: false,  // 添加展开状态标志
                    activityCount: sectionActivityCount,  // 设置小节的活动数量
                    resources: section.courseCatalogThird.map(resource => ({
                      ...resource,
                      isExpanded: false,  // 添加展开状态标志
                    })),
                  };
                }),
              };
            });

            // 计算总章节数和活动数
            this.totalChapters = this.chapters.length;
            this.totalActivities = this.chapters.reduce((total, chapter) => {
              // 遍历每个章节的二级目录
              chapter.courseCatalogSecond.forEach(section => {
                // 将二级目录的三级目录数量加到总活动数中
                total += section.courseCatalogThird.length;
              });
              return total;
            }, 0); // 初始化总活动数为0
          } else {
            console.error("res.data.data.courseCatalog is not an array:", courseCatalog);
          }
        } else {
          console.error("API response code is not 200:", res.data);
          this.$message.error('加载目录失败，服务器返回错误代码');
        }

        console.log("目录\n" + JSON.stringify(res.data, null, 2));
      } catch (error) {
        this.$message.error('加载目录失败');
        console.error('加载目录失败', error);
      }
    },

    // 切换章节展开状态
    toggleChapter(chapter) {
      chapter.isExpanded = !chapter.isExpanded;
      // 如果收起章节，同时收起其下所有小节
      if (!chapter.isExpanded) {
        chapter.sections.forEach(section => {
          section.isExpanded = false;
        });
      }
    },

    // 切换小节展开状态
    toggleSection(section) {
      section.isExpanded = !section.isExpanded;
    },

    // 获取资源图标
    getResourceIcon(type) {
      const icons = {
        ppt: 'el-icon-document',
        document: 'el-icon-document-copy',
        video: 'el-icon-video-camera'
      };
      return icons[type] || 'el-icon-document';
    }
  }
}
</script>

<style scoped>
.course-directory {
  padding: 10px;
}
.directory-list {
  margin-bottom: 10px;
}
.course-stats {
  margin-bottom: 5px;
  color: #666;
}

.chapter {
  margin-bottom: 5px;
  background: #f9f9f9;
  border-radius: 4px;
}

.chapter-header {
  padding: 10px;
  justify-content: space-between;
  display: flex;
  align-items: center;
}

.section-header {
  padding: 10px;
  background: #f9f9f9;
  margin: 5px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}


.arrow {
  margin-right: 10px;
  transition: transform 0.3s;
  font-size: 12px;
}

.chapter-title, .section-title {
  flex: 1;
}

.chapter-info, .section-info {
  color: #1f2023;
  display: flex;
  align-items: center;
  .space{
    margin-left: 5px;
  }
}
.resource-list {
  padding: 0 10px;
}

.resource-item {
  display: flex;
  align-items: center;
  padding: 5px;
  background: #f9f9f9;
  margin: 5px 0;
  border-radius: 4px;
}

.resource-icon {
  margin-right: 5px;
}

.resource-info {
  flex: 1;
}

.resource-title {
  font-size: 12px;
  color: #333;
}

.resource-status {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.section-list {
  padding-left: 20px;
}
</style>

